package com.itheima.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.core.domain.R;
import com.itheima.common.core.domain.entity.SysUser;
import com.itheima.common.utils.DateUtils;
import com.itheima.common.utils.SecurityUtils;
import com.itheima.server.domain.Business;
import com.itheima.server.domain.BusinessDetail;
import com.itheima.server.domain.CluBusSave;
import com.itheima.server.domain.Transfer;
import com.itheima.server.dto.BusinessPageQueryDto;
import com.itheima.server.mapper.BusinessDetailMapper;
import com.itheima.server.mapper.BusinessMapper;
import com.itheima.server.mapper.RuleMapper;
import com.itheima.server.service.IBusinessService;
import com.itheima.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements IBusinessService {
    private static final Integer IN_SEA=1;
    private static final Integer OUT_SEA=0;
    private static final Integer TRACK_STATUS_WAIT=1;
    private static final Integer CONTRACT_STATUS=3;
    @Autowired
    private  BusinessMapper businessMapper;
    @Autowired
    private  SysUserMapper sysUserMapper;
    @Autowired
    private BusinessDetailMapper businessDetailMapper;
    @Autowired
    private RuleMapper ruleMapper;


    public BusinessServiceImpl(BusinessMapper businessMapper) {
        this.businessMapper = businessMapper;
    }


    /**
     * 分页查询商机列表
     *
     * @param businessPageQueryDto
     * @return
     */
    @Override
    public List<Business> selectBusinessList(BusinessPageQueryDto businessPageQueryDto) {
        Page<Business> page = new Page<>(businessPageQueryDto.getPageNum(), businessPageQueryDto.getPageSize());
        // 构造查询条件
        LambdaQueryWrapper<Business> wrapper = getWrapperBySea(OUT_SEA, businessPageQueryDto);
        super.page(page, wrapper);
        return page.getRecords();
    }

    /**
     * 分页查询公海池列表
     *
     * @param businessPageQueryDto
     * @return
     */
    @Override
    public List<Business> selectPoolList(BusinessPageQueryDto businessPageQueryDto) {
        Page<Business> page = new Page<>(businessPageQueryDto.getPageNum(), businessPageQueryDto.getPageSize());
        // 构造查询条件
        LambdaQueryWrapper<Business> wrapper = getWrapperBySea(IN_SEA, businessPageQueryDto);
        super.page(page, wrapper);
        return page.getRecords();
    }

    /**
     * 添加商机
     *
     * @param business
     * @return
     */
    @Override
    @Transactional
    public R addBussiness(Business business) {


        //判断是否到达保有量
        LambdaQueryWrapper<Business> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Business::getOwner, SecurityUtils.getUsername());
        wrapper.ne(Business::getStatus,3);
        wrapper.ne(Business::getSea,IN_SEA);
        int count = super.count(wrapper);
        if (count>=getInventory()){
            return R.fail("已超过最大保有量");
        }


        business.setStatus(TRACK_STATUS_WAIT);
        // 获得当前用户名添加到归属人
        String username = SecurityUtils.getUsername();
        business.setOwner(username);

        business.setCreateTime(new Date());
        business.setUpdateTime(new Date());


        boolean result = super.save(business);
        //添加到商机详情表
        BusinessDetail businessDetail = new BusinessDetail();
        BeanUtils.copyProperties(business, businessDetail);
        businessDetail.setBusinessId(business.getId());
        businessDetail.setCreateBy(username);
        businessDetail.setCreateTime(new Date());
        businessDetail.setUpdateTime(new Date());

        businessDetailMapper.insert(businessDetail);
        return R.ok(result);
    }

    /**
     * 批量捞取
     *
     * @param ids
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public R batchGain(List<Integer> ids, Long userId) {
        List<Business> businesses = new ArrayList<>();

        //根据ids批量查询
        List<Business> businessList = super.listByIds(ids);
        //根据userId获得userName
        SysUser user = sysUserMapper.selectUserById(userId);
        //查询user的商机保有量是否超过
        int inventory=getInventory();

        int count = businessMapper.selectCount(new LambdaQueryWrapper<Business>().eq(Business::getOwner, user.getUserName())
                .ne(Business::getStatus,3).ne(Business::getSea,IN_SEA));
        if (count+ids.size()>inventory){
            return R.fail("保有量达到上限,操作失败");
        }

        //批量修改
        for (Business business : businessList) {
            business.setOwner(user.getUserName());
            business.setSea(OUT_SEA);
            businesses.add(business);

        }
        //更新表
        boolean result = super.updateBatchById(businesses);
        return R.ok(result);

    }

    @Override
    public R batchAssignment(List<Integer> ids, Long userId) {
        List<Business> businesses = new ArrayList<>();

        //根据ids批量查询
        List<Business> businessList = super.listByIds(ids);
        //根据userId获得userName
        SysUser user = sysUserMapper.selectUserById(userId);
        //查询user的商机保有量是否超过
        int inventory=getInventory();
        int count = businessMapper.selectCount(new LambdaQueryWrapper<Business>().eq(Business::getOwner, user.getUserName())
                .ne(Business::getStatus,3).ne(Business::getSea,IN_SEA));
        if (count+ids.size()>inventory){
            return R.fail("保有量达到上限,操作失败");
        }


        //批量修改
        for (Business business : businessList) {
            business.setOwner(user.getUserName());
            business.setSea(OUT_SEA);
            businesses.add(business);

        }
        //更新表
        boolean result = super.updateBatchById(businesses);
        return R.ok(result);
    }

    @Override
    @Transactional
    public R back(Integer businessId, String reason) {
        Business business = super.getById(businessId);
        business.setSea(IN_SEA);
        business.setReasons( reason);
        business.setOwner(null);

        boolean result = super.updateById(business);
        //设置owner为空
        UpdateWrapper<Business> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", businessId);
        updateWrapper.set("owner", null);
        super.update(updateWrapper);

        return R.ok(result);
    }


    //分页查询wrapper构造方法
    LambdaQueryWrapper<Business> getWrapperBySea(int sea, BusinessPageQueryDto businessPageQueryDto){


        LambdaQueryWrapper<Business> wrapper = new LambdaQueryWrapper<Business>();
        wrapper.eq(Business::getSea, sea);
        wrapper.ne(Business::getStatus,CONTRACT_STATUS);
        //条件查询
        if (businessPageQueryDto.getId() != null) {
            wrapper.like(Business::getId, businessPageQueryDto.getId());
        }
        if (businessPageQueryDto.getName() != null) {
            wrapper.like(Business::getName, businessPageQueryDto.getName());
        }
        if (businessPageQueryDto.getPhone() != null) {
            wrapper.like(Business::getPhone, businessPageQueryDto.getPhone());
        }
        if (businessPageQueryDto.getOwner() != null) {
            wrapper.like(Business::getOwner, businessPageQueryDto.getOwner());
        }
        if (businessPageQueryDto.getStatus() != null) {
            wrapper.eq(Business::getStatus, businessPageQueryDto.getStatus());
        }


        //时间判断
        String beginCreateTime = businessPageQueryDto.getParams().get("beginCreateTime");
        String endCreateTime = businessPageQueryDto.getParams().get("endCreateTime");

        if (StringUtils.hasText(beginCreateTime) && StringUtils.hasText(endCreateTime)){
            try {
                DateUtils.parseDate(beginCreateTime,"yyyy-MM-dd");
                DateUtils.parseDate(endCreateTime,"yyyy-MM-dd");
                wrapper.between(Business::getCreateTime,beginCreateTime, endCreateTime);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }


        return wrapper;
    }

    //获得保有量
    private Integer getInventory(){
        LambdaQueryWrapper<CluBusSave> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CluBusSave::getType, 1);
        CluBusSave cluBusSave = ruleMapper.selectOne(wrapper);
        return cluBusSave.getMaxNunmber();

    }


}
